import React, {useEffect} from 'react';
import {Layout,Tabs} from "antd";
import {Outlet, useLocation, useNavigate} from "react-router-dom";
import {useAppDispatch, useAppTitle} from "@/hooks";
import type {TPanes} from "@/store/slice/common";
import {addPanes, delPanes, useSelectorCommon} from "@/store/slice/common";
const {Content} = Layout
const { TabPane } = Tabs;

function IndexContent() {
    const {pathname:key} = useLocation();
    const navigate = useNavigate();
    const {panes} = useSelectorCommon()
    const dispatch = useAppDispatch()
    const {subTitle:title} = useAppTitle()
    useEffect(()=>{
        dispatch(addPanes({
            title,
            key,
            closable:true
        }))
    },[key])
    return (
        <Content style={{margin: '5PX'}}>
            <div className="site-layout-background" style={{padding: 24, height:"100%"}}>
            <Tabs type="editable-card"
                  hideAdd={true}
                  onChange={(activeKey)=>{
                      navigate(activeKey)
                  }}
                  activeKey={key}
                  onEdit={(actionKey,action)=>{
                      if(action === "remove"){
                         const index = panes.findIndex((v:TPanes)=>v.key === actionKey)
                          if(index > 0){
                              dispatch(delPanes(index))
                              //如果点击的是关闭当前标签(已选择)
                              if(actionKey === key){
                                  navigate(panes[index-1].key)
                              }
                          }
                      }
                  }}
            >
                {panes.map((pane:TPanes) => (
                    <TabPane tab={pane.title} key={pane.key} closable={pane.closable}>
                        {
                         key === pane.key &&  <Outlet/>
                        }
                    </TabPane>
                ))}
            </Tabs>
            </div>
        </Content>
    );
}

export default IndexContent;